import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gameplay_flutter/lib_baseview/widget/dialogs.dart';
import 'package:gameplay_flutter/lib_runtime/extension/widget/widget_wrapper.dart';
import 'package:ones/ui/action.dart';
import 'package:ones/values/colors.dart';

import 'package:provider/provider.dart';

import '../../../../generated/assets.dart';
import '../../../../lib_basemodel/chat_room/kh_chat_room_seat_model.dart';
import '../../../../lib_baseview/theme/jr.dart';
import '../../../../lib_baseview/widget/keep_alive_wrapper.dart';
import '../../../../lib_chat/chat/index.dart';
import '../../../../lib_im/index.dart';
import '../../../../lib_runtime/extension/string_extension/string_text.dart';
import '../../../../m_discover/post/post_view.dart';
import '../../../../resource/language/generated/l10n.dart';
import 'gift_item_widget.dart';
import 'gift_page_model.dart';
import 'gift_user_widget.dart';

/// 回调函数
typedef GiftCallBack = void Function(
  // 麦上用户列表
  List<KHChatRoomSeatModel?> micUser,
  // 用户选中的礼物
  ImGitfModel? giftModel,
  // 赠送的数量
  int count,
);

class GiftPage extends StatefulWidget {
  // 房间号
  final String? roomNo;

  /// 麦上用户
  final List<KHChatRoomSeatModel?>? micUserList;
  // final Channel? channel;
  // MsgListUserItem? userItem;

  // final Channel? channel;
  // MsgListUserItem? userItem;

  //心愿礼物
  int tabIndex;
  int? giveGiftId;
  VoidCallback? refreshAction;

  GiftCallBack? giftCallBack;

  GiftPage({
    Key? key,
    required this.roomNo,
    this.micUserList = const [],
    this.tabIndex = 0,
    this.giveGiftId,
    this.refreshAction,
    this.giftCallBack,
  }) : super(key: key);

  @override
  State<GiftPage> createState() => _GiftPageState();
  static show(
    BuildContext context,
    List<KHChatRoomSeatModel?>? userList,
    String roomNo, {
    bool isComeIM = false,
    VoidCallback? refreshAction,
    int? giveGiftId,
    int tabIndex = 0,
    GiftCallBack? giftCallBack,

    // MsgListUserItem? userItem,
  }) {
    showModalBottomSheet(
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadiusDirectional.only(
          topStart: Radius.circular(24),
          topEnd: Radius.circular(24),
        ),
      ),
      backgroundColor: Colors.transparent,
      barrierColor: Colors.transparent,
      context: context,
      isScrollControlled: true,
      builder: (context) => GiftPage(
        // scene: scene,
        // roomNo
        roomNo: roomNo,
        micUserList: userList,
        // channel: channel,
        // channelId: channel?.channelId,
        // userItem: userItem,
        refreshAction: refreshAction,
        giveGiftId: giveGiftId,
        tabIndex: tabIndex,
        giftCallBack: giftCallBack,
      ),
    );
  }
}

class _GiftPageState extends State<GiftPage> with TickerProviderStateMixin {
  TabController? _tabController;

  // OnGiveInterrupt? onGiveInterrupt;

  GiftPageModel? giftPageModel;

  @override
  void initState() {
    super.initState();
    // // GiftCallBack? giftCallBack;
    // giftCallBack = () {};
    // onGiveInterrupt = () {
    //   // if (widget.userItem?.isYourInBlackList ?? false) {
    //   //   showToast(T.current.you_were_in_blacklist);
    //   //   return true;
    //   // }

    //   // if (widget.userItem?.isHeInYourBlackList ?? false) {
    //   //   showToast(T.current.other_side_in_blacklist);
    //   //   return true;
    //   // }
    //   return false;
    // };
  }

  _initTabController(int len) {
    if (_tabController == null || _tabController!.length != len) {
      _tabController ??= TabController(length: len, vsync: this);
      _tabController!.index = widget.tabIndex;
      _tabController!.addListener(() {
        giftPageModel?.currentGroupInfo =
            giftPageModel?.tabList[_tabController!.index];
      });
    }
  }

  @override
  void dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) {
            // 先创建模型实例并设置属性
            final model = GiftPageModel()
              ..currentGiftID = widget.giveGiftId
              ..roomNo = widget.roomNo
              ..userList = widget.micUserList ?? []
              ..initSelectedUserList()
              ..tabValueChange = _tabValueChange
              ..onLoadTabCompleted = _onLoadTabCompleted;

            // 延迟执行数据加载，确保回调已绑定
            Future.microtask(() => model.getGiftData());
            return model;
          },
        )
      ],
      child: Consumer<GiftPageModel>(
        builder: (BuildContext context, GiftPageModel model, child) {
          giftPageModel ??= model;
          return _buildContent(context, model);
        },
      ),
    );
  }

  _tabValueChange(int index) {
    _tabController?.index = index;
  }

  double get viewH => 350;
  Widget _buildContent(BuildContext context, GiftPageModel vm) {
    if (vm.isLoading) {
      return _emptyView(vm);
    }

    var tabs = vm.tabList;
    Widget child = Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        _giftUser(context),
        const SizedBox(height: 7),
        _giftContentPage(vm),
      ],
    );
    return child;
  }

  _giftContentPage(GiftPageModel vm) {
    var tabs = vm.tabList;
    Widget child = Container(
      width: double.infinity,
      decoration: const BoxDecoration(
        color: Color(0xFF241235),
        borderRadius: BorderRadiusDirectional.only(
          topStart: Radius.circular(18),
          topEnd: Radius.circular(18),
        ),
      ),
      child: Stack(
        children: [
          SizedBox(
            height: viewH,
            child: _buildTabs(tabs, vm),
          ),
          // if (vm.showBottomBar)
          //   PositionedDirectional(
          //     start: 0,
          //     bottom: 0,
          //     child: _buyPanel(vm),
          //   ),
          // _renderTipsWidget(vm)
        ],
      ),
    );
    return child;
    // return vm.fromRoom
    //     ? ClipRRect(
    //         borderRadius: BorderRadius.circular(0),
    //         child: BackdropFilter(
    //           filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
    //           child: child,
    //         ),
    //       )
    //     : child;
  }

  Container _emptyView(GiftPageModel vm) {
    return Container(
      height: viewH,
      padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 22),
      decoration: BoxDecoration(
        color: vm.bgColor,
        borderRadius: const BorderRadiusDirectional.only(
          topStart: Radius.circular(24),
          topEnd: Radius.circular(24),
        ),
      ),
      child: Center(
        child: Text(
          "Loading...",
          style: TextStyle(color: vm.textColor, fontSize: 15),
        ),
      ),
    );
  }

  Widget _buildTabs(List<ImGitfWrapperModel> tabs, GiftPageModel pageModel) {
    // 添加空安全判断
    if (tabs.isEmpty || _tabController == null) {
      return const SizedBox.shrink();
    }

    return Column(
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsetsDirectional.only(
              start: 4, top: 10, bottom: 10, end: 4),
          child: TabBar(
            controller: _tabController,
            isScrollable: true,
            physics: const ClampingScrollPhysics(),
            dividerColor: Colors.transparent,
            dividerHeight: 0,
            tabAlignment: TabAlignment.start,
            indicatorSize: TabBarIndicatorSize.label,
            indicatorWeight: 1,
            indicatorPadding: const EdgeInsets.only(bottom: 0),
            indicator: const ImageTabIndicator(
                image: AssetImage(Assets.discoverWhiteIndicator),
                width: 15,
                height: 6),
            unselectedLabelStyle:
                const TextStyle(color: Color(0xFFA397DE), fontSize: 16),
            labelStyle: const TextStyle(
              color: Color(0xFFFFFFFF),
              fontWeight: FontWeight.w700,
              fontSize: 16,
            ),
            onTap: (index) {
              pageModel.currentGroupInfo = tabs[index];
            },
            tabs: tabs
                .map((e) => Container(
                    height: 30,
                    margin:
                        const EdgeInsetsDirectional.symmetric(horizontal: 12),
                    child: Tab(text: e.name)))
                .toList(),
          ),
        ),
        const SizedBox(height: 8),
        Expanded(
          child: TabBarView(
              controller: _tabController,
              children: tabs.map<Widget>((tab) {
                print('sssss======> ${tab.name}');

                // 根据当前 tab 筛选礼物列表
                final tabGifts = pageModel.getGifts(tab);

                return Consumer<GiftPageModel>(
                  builder: (context, model, _) {
                    return KeepAliveWrapper(
                      child: Stack(
                        children: [
                          _buildGiftGrid(
                              context, tabGifts), // 使用Consumer传递的context

                          /// 左下角视图
                          Container(
                            width: 160,
                            height: 36,
                            decoration: BoxDecoration(
                              // color: Colors.blue,
                              color: const Color(0xFF000000)
                                  .withValues(alpha: 0.65),
                              borderRadius: const BorderRadius.all(
                                  Radius.circular(36 / 2.0)),
                            ),
                            child: Row(
                              children: [
                                JR
                                    .img('room/room_gift_price_icon.png',
                                        width: 16, height: 16)
                                    .padding(start: 7, end: 2),
                                ValueListenableBuilder(
                                  valueListenable:
                                      context.read<GiftPageModel>().balance,
                                  builder: (context, value, child) {
                                    return '$value'.text(
                                        color: Color(0xFFFFFFFF),
                                        fontSize: 20,
                                        weight: TextFontWeight.medium);
                                  },
                                ),
                                const Spacer(),
                                T.current.me_recharge
                                    .text(
                                        color: Colors.white,
                                        fontSize: 11,
                                        weight: TextFontWeight.medium)
                                    .colorBg(bgColor: const Color(0xFF8A72FE))
                                    .sized(width: 62, height: 26)
                                    .corner(radius: 26 / 2.0)
                                    .padding(end: 6)
                                    .onClick(() {
                                  showToast('充值按钮被点击');
                                }),
                              ],
                            ),
                          ).positioned(start: 15, bottom: 31),

                          /// 右下角视图

                          Container(
                            width: 112,
                            height: 36,
                            decoration: BoxDecoration(
                              // color: Colors.blue,
                              border: Border.all(width: 1, color: Colors.white),
                              color: const Color(0xFF000000)
                                  .withValues(alpha: 0.65),
                              borderRadius: const BorderRadius.all(
                                  Radius.circular(36 / 2.0)),
                            ),
                            child: Row(
                              children: [
                                CustomPopup(
                                  showArrow: false,
                                  contentPadding: EdgeInsets.zero,
                                  content: Column(
                                    mainAxisSize: MainAxisSize.min,
                                    children: model.giftNumbers
                                        .map((value) => _counter(
                                              context,
                                              value,
                                              model,
                                            )) // 传递vm参数
                                        .toList(),
                                  ).clipRRect(5),
                                  barrierColor: Colors.transparent,
                                  contentDecoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(8),
                                    color: const Color(0xFFF2F2F2),
                                  ),
                                  child: Container(
                                    padding:
                                        const EdgeInsets.fromLTRB(10, 4, 4, 4),
                                    constraints:
                                        const BoxConstraints(minWidth: 60),
                                    alignment: Alignment.center,
                                    decoration: const BoxDecoration(
                                      color: Color(0xFFF2F2F2),
                                      borderRadius:
                                          BorderRadiusDirectional.horizontal(
                                              start: Radius.circular(99)),
                                    ),
                                    child: Row(
                                      children: [
                                        Text(
                                          '${model.giftCount}',
                                          style: const TextStyle(
                                            color: Color(0xFF1B1B1B),
                                            fontWeight: FontWeight.w500,
                                            fontSize: 18,
                                          ),
                                        ),
                                        const Icon(Icons.keyboard_arrow_up,
                                            size: 15),
                                      ],
                                    ),
                                  ),
                                ),
                                Container(
                                  width: 1,
                                  color: const Color(0xFFFFFFFF),
                                ),
                                Expanded(
                                  child: Container(
                                    width: double.infinity,
                                    height: 36,
                                    decoration: const BoxDecoration(
                                        color: Color(0xFF8A72FE),
                                        borderRadius:
                                            BorderRadiusDirectional.only(
                                                topEnd:
                                                    Radius.circular(36 / 2.0),
                                                bottomEnd:
                                                    Radius.circular(36 / 2.0))),
                                    child: T.current.c_send
                                        .text(
                                            color: Colors.white,
                                            fontSize: 14,
                                            weight: TextFontWeight.bold)
                                        .center()
                                        .onClick(() {
                                      if (widget.giftCallBack != null &&
                                          model.curSelectGiftModel != null) {
                                        if (model.selectedUserList.isEmpty) {
                                          // ignore: void_checks
                                          return showToast('请选择接收礼物的人');
                                        }

                                        model.sendRoomGift(
                                            model.selectedUserList,
                                            model.roomNo,
                                            model.curSelectGiftModel,
                                            model.giftCount,
                                            callback: (isSuccess) {
                                          if (isSuccess) {
                                            Navigator.of(context).pop();
                                            widget.giftCallBack!(
                                              model.selectedUserList,
                                              model.curSelectGiftModel,
                                              model.giftCount,
                                            );
                                          } else {
                                            showToast('赠送礼物失败');
                                          }
                                        });
                                      }
                                    }),
                                  ),
                                )
                              ],
                            ),
                          ).positioned(end: 15, bottom: 31),
                        ],
                      ),
                    );
                  },
                );
              }).toList()),
        ),
      ],
    );
  }

  Widget _counter(BuildContext context, int value, GiftPageModel vm) {
    final last = value == vm.giftNumbers.last;
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pop();
        vm.setGiftCount(value);
      },
      // behavior: HitTestBehavior.opaque,
      child: Container(
        width: 50,
        padding: const EdgeInsets.symmetric(vertical: 10),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: const Color(0xFF000000),
          border: Border(
            bottom: BorderSide(
                color: last ? Colors.transparent : Color(0xFF575757)),
          ),
        ),
        child: Text(
          '$value',
          style: TextStyle(
              fontWeight: FontWeight.w500,
              color: vm.giftCount == value
                  ? const Color(0xFFFFFFFF)
                  : const Color(0xFF656565)),
        ),
      ),
    );
  }

  Widget _buildGiftGrid(BuildContext context, List<ImGitfModel> tabGifts) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: GridView.builder(
        padding: const EdgeInsets.only(top: 10, bottom: 80),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          mainAxisSpacing: 10,
          crossAxisSpacing: 10,
          childAspectRatio: 0.85,
        ),
        itemCount: tabGifts.length,
        itemBuilder: (context, index) {
          final gift = tabGifts[index];
          return GiftItemWidget(
            gift: gift,
            onTap: () => context.read<GiftPageModel>().selectGift(gift.id!),
          );
        },
      ),
    );
  }

  _giftUser(BuildContext context) {
    var vm = context.watch<GiftPageModel>();
    bool isSelectAll = vm.isSelectAll();

    return Stack(
      alignment: AlignmentDirectional.bottomStart,
      children: [
        Container(
          width: double.infinity,
          height: 43,
          alignment: AlignmentDirectional.centerStart,
          margin: const EdgeInsets.only(left: 13, right: 13),
          decoration: BoxDecoration(
            color: vm.bgColor,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox(width: 10),
              T.current.room1_gave_to.text(color: Colors.white, fontSize: 18),
              const SizedBox(width: 4),

              /// 麦上用户列表
              Expanded(
                child: ListView.separated(
                  scrollDirection: Axis.horizontal,
                  itemCount: vm.userList.length,
                  itemBuilder: (context, index) {
                    KHChatRoomSeatModel? user = vm.userList[index];
                    if (user != null) {
                      return GiftUserWidget(
                          user: user,
                          selected: vm.selectedUserList.contains(user),
                          onPressed: () {
                            vm.selectGiftUser(user);
                          });
                    }
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return const SizedBox(
                      width: 0,
                    );
                  },
                ),
              ),

              const SizedBox(width: 4),
              JR.img('room/room_gift_right_icon.png', width: 12, height: 12),
              const SizedBox(width: 17),
              Stack(
                alignment: isSelectAll
                    ? AlignmentDirectional.centerStart
                    : AlignmentDirectional.centerEnd,
                children: [
                  JR.img(
                      isSelectAll
                          ? 'room/room_mic_all.png'
                          : 'room/room_mic_all1.png',
                      width: 40,
                      height: 20),
                  isSelectAll
                      ? Positioned(
                          left: 6,
                          child: 'all'.text(
                            color: Colors.white,
                            fontSize: 11,
                            weight: TextFontWeight.medium,
                          ))
                      :
                      // .positioned(end: 10)
                      Positioned(
                          right: 8,
                          child: 'all'.text(
                            color: Colors.white,
                            fontSize: 11,
                            weight: TextFontWeight.medium,
                          )),
                ],
              ).onClick(() {
                context.read<GiftPageModel>().selectAllGiftUser();
              }),

              const SizedBox(width: 15),
            ],
          ),
        ),
      ],
    );
  }

  void _onLoadTabCompleted(List<ImGitfWrapperModel> value) {
    _initTabController(value.length);

    if (mounted) {
      // 触发界面重建
      _tabController?.animateTo(0);
      // _tabController?.animateTo(0);
    }
  }
}
